package com.tydic.portal.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.tydic.borderer.domain.BordererInfo;
import com.tydic.borderer.domain.request.*;
import com.tydic.borderer.domain.response.AccountInfo;
import com.tydic.borderer.domain.response.UserInfo;
import com.tydic.borderer.service.IBordererInfoService;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.*;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.core.utils.ReturnUrlUtil;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.system.domain.Account;
import com.tydic.system.domain.Company;
import com.tydic.system.domain.req.CloseUnwantedAuthSignRequest;
import com.tydic.system.domain.req.SeachUnwantedAuthSignRequest;
import com.tydic.system.domain.req.UnwantedAuthSignRequest;
import com.tydic.system.domain.resp.UnwantedAuthSignResponse;
import com.tydic.system.domain.resp.UnwantedAuthSignStatusResponse;
import com.tydic.system.service.IFddService;
import com.tydic.workflow.service.IBordererRegisterService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 边民账号
 */


@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/portal/border")
public class BordererAccountController {
    private final IBordererInfoService bordererInfoService;
    private final IFddService fddService;
    private final IBordererRegisterService bordererRegisterService;
    @Value("${fdd.returnUrlPrefix}")
    private String returnUrlPrefix;

    @PostMapping("/login/registerValidatePhone")
    /**
     * 注册账号-验证手机号码
     */
    public R registerValidatePhone(@Validated @RequestBody BordererValidatePhoneRequest request) {
        bordererInfoService.registerValidatePhone(request);
        return R.ok();
    }

    @PostMapping("/login/registerInputPwd")
    /**
     * 注册账号-设置密码
     */
    public R registerInputPwd(@Validated @RequestBody InputPwdRequest request) {
        bordererInfoService.registerInputPwd(request);
        return R.ok();
    }

    @PostMapping("/registerPersonInfo")
    /**
     * 实名认证
     */
    public R registerPersonInfo(@Validated @RequestBody PersonInfoRequest request) {
        bordererInfoService.registerPersonInfo(request);
        return R.ok();
    }

    @PostMapping("/login/resetPwd")
    /**
     * 重置密码
     */
    public R resetPwd(@Validated @RequestBody ResetPwdRequest request) {
        bordererInfoService.resetPassword(request);
        return R.ok();
    }

    @GetMapping("/getAccountInfo")
    /**
     * 账号信息
     */
    public R getAccountInfo() {
        AccountInfo accountInfo = bordererInfoService.getAccountInfo();
        return R.ok(accountInfo);
    }


    @GetMapping("/getBorderDetail")
    /**
     * 个人信息
     */
    public R getUserInfo() {
        UserInfo userInfo = bordererInfoService.getUserInfo();
        return R.ok(userInfo);
    }


    @PostMapping("/updateUserInfo")
    /**
     * 修改个人信息
     */
    public R updateUserInfo(@Validated @RequestBody UserInfo request) {
        bordererInfoService.updateUserInfo(request);
        return R.ok();
    }

    @PostMapping("/updatePhoneNumber")
    /**
     * 修改手机号码
     */
    public R updatePhoneNumber(@Validated @RequestBody ValidatePhoneRequest request) {
        bordererInfoService.updatePhoneNumber(request);
        return R.ok();
    }

    @PostMapping("/validatePhone")
    /**
     * 修改密码-验证手机号码
     */
    public R validatePhone(@Validated @RequestBody ValidatePhoneRequest request) {
        bordererInfoService.validatePhone(request);
        return R.ok();
    }

    @PostMapping("/updatePwd")
    /**
     * 修改密码
     */
    public R updatePwd(@Validated @RequestBody UpdatePwdRequest request) {
        bordererInfoService.updatePwd(request);
        return R.ok();
    }


    @PostMapping("/verifyUser")
    public R verifyUser(@RequestBody @Valid VerifyBordererRequest verifyBordererRequest) {
        LoginUser user = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(user.getUserCode());
        Account account = fddService.getAccountByMobile(user.getMobile());
        String verifyUrl;
        String userCertificationStatus;
        if (account == null) {
            account = new Account();
            account.setMobile(user.getMobile());
            account.setUserName(verifyBordererRequest.getName());
            fddService.createAccount(account);
            verifyUrl = fddService.verifyAccount(verifyBordererRequest.getName(), user.getMobile(), verifyBordererRequest.getIdCardNumber(), verifyBordererRequest.getCardNumber(), ReturnUrlUtil.getBordererVerifyAccountUrl(returnUrlPrefix));
            userCertificationStatus = UserCertificationStatusEnum.READY.getStatus();
        } else {
            if (!StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
                verifyUrl = fddService.verifyAccount(verifyBordererRequest.getName(), user.getMobile(), verifyBordererRequest.getIdCardNumber(), verifyBordererRequest.getCardNumber(), ReturnUrlUtil.getBordererVerifyAccountUrl(returnUrlPrefix));
            } else {
                verifyUrl = fddService.verifyChangeAccount(verifyBordererRequest.getName(), user.getMobile(), verifyBordererRequest.getIdCardNumber(), verifyBordererRequest.getCardNumber(), ReturnUrlUtil.getBordererVerifyAccountUrl(returnUrlPrefix));
            }
            userCertificationStatus = account.getVerifyStatus();
        }
        if (bordererInfo != null) {
            if (bordererInfo.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getStatus())) {
                throw new ApiException("该边民已完成实名认证，如需变动请发起变更");
            }
            // 审核失败后的重新审核
            else {
                if (bordererInfo.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
                    boolean finished = bordererRegisterService.isFinished(bordererInfo.getProcInstId());
                    if (!finished) {
                        bordererInfo.setAuditStatus(AuditStatusEnum.READY.getStatus());
                        bordererRegisterService.submit(bordererInfo.getProcInstId(), true);
                    }
                }
                BeanUtils.copyProperties(verifyBordererRequest, bordererInfo);
                bordererInfo.setUserCertificationStatus(userCertificationStatus);
                bordererInfoService.save(bordererInfo);
            }
        } else {
            bordererInfo = new BordererInfo();
            BeanUtils.copyProperties(verifyBordererRequest, bordererInfo);
            bordererInfo.setId(IdUtil.getSnowflakeNextIdStr());
            bordererInfo.setUserCertificationStatus(userCertificationStatus);
            bordererInfo.setUserCode(user.getUserCode());
            bordererInfoService.save(bordererInfo);
        }
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    /**
     * 获取用户实名认证状态
     */
    @GetMapping("/getUserCertificationStatus")
    public R getUserCertificationStatus() {
        LoginUser user = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(user.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("边民信息不存在");
        }
        return R.ok("成功", bordererInfo.getUserCertificationStatus());
    }

    /**
     * 获取企业实名认证状态
     */
    @GetMapping("/getEnterpriseCertificationStatus")
    public R getEnterpriseCertificationStatus() {
        LoginUser user = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(user.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("边民信息不存在");
        }
        return R.ok("成功", bordererInfo.getEnterpriseCertificationStatus());
    }


    @PostMapping("/verifyEnterprise")
    /**
     * 个体工商户实名认证
     */
    public R verifyEnterprise(@RequestBody @Valid VerifyBordererEnterpriseRequest verifyBordererEnterpriseRequest) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        Account account = fddService.getAccountByMobile(currentUser.getMobile());
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("该边民信息不存在，请前往边民个人实名认证");
        } else if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成个人实名认证");
        }
//        if (bordererInfo.getAuditStatus().equals(AuditStatusEnum.SUCCESS.getStatus())) {
//            throw new ApiException("该边民已完成实名认证，如需变动请发起变更");
//        }
        BeanUtils.copyProperties(verifyBordererEnterpriseRequest, bordererInfo);
        bordererInfo.setUserCertificationStatus(account.getVerifyStatus());
        Company company = fddService.getCompanyByCompanyName(verifyBordererEnterpriseRequest.getEnterpriseName());
        String verifyUrl;
        if (company == null) {
            company = new Company();
            company.setCompanyName(verifyBordererEnterpriseRequest.getEnterpriseName());
            company.setAdminMobile(verifyBordererEnterpriseRequest.getPhoneNumber());
            company.setAdminName(verifyBordererEnterpriseRequest.getOperator());
            fddService.createCompany(company);
            verifyUrl = fddService.verifyCompany(verifyBordererEnterpriseRequest.getPhoneNumber(), verifyBordererEnterpriseRequest.getEnterpriseName(), verifyBordererEnterpriseRequest.getSocialCode(), bordererInfo.getBankName(), bordererInfo.getIdCardNumber(), bordererInfo.getBranchBankName(), ReturnUrlUtil.getBordererVerifyCompanyUrl(returnUrlPrefix));
            bordererInfo.setEnterpriseCertificationStatus(EnterpriseCertificationStatusEnum.READY.getStatus());
        } else {
            if (!StrUtil.equals(company.getIsCerdit(), EnterpriseCertificationStatusEnum.SUCCESS.getStatus())) {
                verifyUrl = fddService.verifyCompany(verifyBordererEnterpriseRequest.getPhoneNumber(), verifyBordererEnterpriseRequest.getEnterpriseName(), verifyBordererEnterpriseRequest.getSocialCode(), bordererInfo.getBankName(), bordererInfo.getIdCardNumber(), bordererInfo.getBranchBankName(), ReturnUrlUtil.getBordererVerifyCompanyUrl(returnUrlPrefix));
            } else {
                verifyUrl = fddService.verifyChangeCompany(verifyBordererEnterpriseRequest.getPhoneNumber(), verifyBordererEnterpriseRequest.getEnterpriseName(), verifyBordererEnterpriseRequest.getSocialCode(), bordererInfo.getBankName(), bordererInfo.getIdCardNumber(), bordererInfo.getBranchBankName(), ReturnUrlUtil.getBordererVerifyCompanyUrl(returnUrlPrefix));
            }
            bordererInfo.setEnterpriseCertificationStatus(company.getIsCerdit());
        }
        if (bordererInfo.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
            boolean finished = bordererRegisterService.isFinished(bordererInfo.getProcInstId());
            if (!finished) {
                bordererInfo.setAuditStatus(AuditStatusEnum.READY.getStatus());
            }
        }
        bordererInfoService.save(bordererInfo);
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    @GetMapping("/skipVerifyEnterprise")
    /**
     * 跳过个体工商户实名认证
     */
    public R skipVerifyEnterprise() {
        LoginUser currentUser = LoginHelper.getLoginUser();
        Account account = fddService.getAccountByMobile(currentUser.getMobile());
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("该边民信息不存在，请前往边民个人实名认证");
        } else if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成个人实名认证");
        }
        bordererInfo.setEnterpriseCertificationStatus(EnterpriseCertificationStatusEnum.SKIP.getStatus());
        if (bordererInfo.getAuditStatus().equals(AuditStatusEnum.FAIL.getStatus())) {
            boolean finished = bordererRegisterService.isFinished(bordererInfo.getProcInstId());
            if (!finished) {
                bordererInfo.setAuditStatus(AuditStatusEnum.READY.getStatus());
            }
        }
        bordererInfoService.save(bordererInfo);
        return R.ok();
    }

    /**
     * 边民开通免验证签服务
     *
     * @return
     */
    @PostMapping("/openUnwantedAuthBorderer")
    /**
     * 边民开通免验证签服务
     */
    public R openUnwantedAuthBorderer() {
        String verifyUrl = "";
        LoginUser currentUser = LoginHelper.getLoginUser();
        Account account = fddService.getAccountByMobile(currentUser.getMobile());
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("该边民信息不存在，请前往边民个人实名认证");
        } else if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成个人实名认证");
        }
        SeachUnwantedAuthSignRequest seachUnwantedAuthSignRequest = new SeachUnwantedAuthSignRequest();
        seachUnwantedAuthSignRequest.setAuthorizerFlag(AuthTypeEnum.BORDERER.getType());
        seachUnwantedAuthSignRequest.setAuthorizerTargetId(account.getAccountId());
        UnwantedAuthSignStatusResponse response = fddService.searchUnwantedAuthSignStatus(seachUnwantedAuthSignRequest);

        //请求签名认证
        UnwantedAuthSignRequest request = new UnwantedAuthSignRequest();
        request.setAuthorizerFlag(AuthTypeEnum.BORDERER.getType());
        request.setAuthorizerTargetId(account.getAccountId());
        request.setAdminAccountId(account.getAccountId());
        if (response == null) {
            UnwantedAuthSignResponse unwantedAuthSignResponse = fddService.openUnwantedAuthSign(request);
            verifyUrl = unwantedAuthSignResponse.getUrl();
        } else {
            if (NumberUtil.equals(response.getStatus(), UnwantedAuthSignEnum.EFFECT.getType())) {
                return R.ok("已完成免验证签授权状态");
            }
            UnwantedAuthSignResponse unwantedAuthSignResponse = fddService.openUnwantedAuthSign(request);
            verifyUrl = unwantedAuthSignResponse.getUrl();

        }
        bordererInfo.setOpenAuthSignStatus(AuditStatusEnum.READY.getStatus());
        bordererInfoService.save(bordererInfo);
        if (StrUtil.isNotBlank(verifyUrl)) {
            return R.ok("成功", verifyUrl);
        } else {
            return R.ok();
        }
    }

    /**
     * 边民关闭免验证签服务
     *
     * @return
     */
    @PostMapping("/closeUnwantedAuthBorderer")
    /**
     * 边民关闭免验证签服务
     */
    public R closeUnwantedAuthBorderer() {
        String verifyUrl = "";
        LoginUser currentUser = LoginHelper.getLoginUser();
        Account account = fddService.getAccountByMobile(currentUser.getMobile());
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        if (bordererInfo == null) {
            throw new ApiException("该边民信息不存在，请前往边民个人实名认证");
        } else if (account == null || !StrUtil.equals(account.getVerifyStatus(), UserCertificationStatusEnum.SUCCESS.getStatus())) {
            throw new ApiException("未完成个人实名认证");
        }
        SeachUnwantedAuthSignRequest seachUnwantedAuthSignRequest = new SeachUnwantedAuthSignRequest();
        seachUnwantedAuthSignRequest.setAuthorizerFlag(AuthTypeEnum.BORDERER.getType());
        seachUnwantedAuthSignRequest.setAuthorizerTargetId(account.getAccountId());
        UnwantedAuthSignStatusResponse response = fddService.searchUnwantedAuthSignStatus(seachUnwantedAuthSignRequest);


        if (response != null && !NumberUtil.equals(response.getStatus(), UnwantedAuthSignEnum.EFFECT.getType())) {
            return R.ok("当前企业并非免验证签状态");
        }

        //请求签名认证
        CloseUnwantedAuthSignRequest request = new CloseUnwantedAuthSignRequest();
        request.setAuthorizerFlag(AuthTypeEnum.BORDERER.getType());
        request.setAuthorizerTargetId(account.getAccountId());
        fddService.closeUnwantedAuthSign(request);

        bordererInfo.setOpenAuthSignStatus(AuditStatusEnum.READY.getStatus());
        bordererInfoService.save(bordererInfo);
        return R.ok();
    }

//
//    /**
//     * 获取边民信息
//     */
//    @GetMapping("/getBordererInfo")
//    public R getBordererInfo() {
//        LoginUser currentUser = LoginHelper.getLoginUser();
//        BordererInfo detail = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
//        return R.ok(detail);
//    }


    /**
     * 边民信息变更
     */
    @PostMapping("/changeBorderInfo")
    public R changeBorderInfo(@Validated @RequestBody UserInfo request) {
        bordererInfoService.updateUserInfo(request);
        return R.ok();
    }


}

